#! /bin/env python
# -*- coding: utf-8 -*-
#
# $Id$


#import copy, md5, os, re, socket, string, sys, threading, time, urllib, urllib2, random, traceback
from mylog import *
import urllib, urllib2, copy, re, md5, random, time

class xchat:
	user		= ""
	nick		= ""
	passwd		= ""
	auth		= ""
	ERROR		= ""
	logged		=  0
	kernel		=  0
	xchaturl	= "http://xchat.centrum.cz/"
	fotoalbaurl	= "http://fotoalba.centrum.cz/"
	fotoalbaupurl	= "http://up1.fotoalba.centrum.cz/"
	loginurl	= "~guest~/login/"

class Xchat:
	def __init__(self):
		self.kernel = copy.deepcopy(xchat())
		self.connection = True
		self.kernel.opener = urllib2.build_opener(RedirectHandler())
		self.kernel.opener.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.8) Gecko/20071020 BonEcho/2.0.0.8'),
						 ('Accept-Charset', 'utf-8;q=0.7,*;q=0.7')]
		self.kernel.urlopen = self.kernel.opener.open
		self.kernel.logged = False
		self.kernel.auth = "~guest~"
		self.kernel.albums = []
		self.kernel.image = []
		self.kernel.aid = 1182025
		self.kernel.initialized = False
		self.kernel.uploaded = 0
		self.kernel.limit = 0

	def login(self):
		pole = {
			'u_name': self.kernel.nick,
			'u_pass': self.kernel.passwd,
			'js': "1",
			'hp': "1",
			'usehash': "3",
		}
		log(u"Přihlašuji...", 0);
		try:
			data = self.kernel.urlopen(self.kernel.xchaturl+self.kernel.loginurl, unicode_urlencode(pole))
			self.kernel.auth = re.findall('http://xchat\.centrum\.cz/([^/]+)', data)[0]
			log(u"Získaný hash %s" %(self.kernel.auth), 0)
			if self.kernel.auth == "~guest~":
				return False
			return True
		except:
			self.kernel.ERROR = "%s\n" %("ERROR: Nelze se prihlasit do Xchat.cz")
			raise
		return False

	def initFa(self):
		url = "%s%s/export/init.php" %(self.kernel.fotoalbaurl, self.kernel.auth)
		try:
			r = self.kernel.urlopen(url)
		except:
			raise
		
		ret = r.read()
		if ret == 1:
			return True
		return False
		
	def getAlbums(self):
		url = "%s%s/export/alba.php?nick=%s" %(self.kernel.fotoalbaurl, self.kernel.auth, self.kernel.nick)
		try:
			r = self.kernel.urlopen(url)
		except:
			raise
		
		data = r.read().splitlines()
		albums = []
		for line in data:
			albums.append(line.split("\t"))
		self.kernel.albums = albums
		return True

	def getLimits(self):
		url = "%s%s/export/limit.php" %(self.kernel.fotoalbaurl, self.kernel.auth)
		try:
			r = self.kernel.urlopen(url)
		except:
			raise
		
		limits = r.read().split(" ")
		self.kernel.uploaded= limits[0]
		self.kernel.limit = limits[1]
		return True

	def uploadImage(self):
		image = self.kernel.image
		FILE = image['file']
		d = {
			'_Button_Send': 'Yes',
			'aid': self.kernel.aid,
		}
		boundary = md5.new(str(random.randint(0,10000))).hexdigest()
		sid = int(time.time())
		URL = "%s%s/cgi-bin/upload.cgi?sessid=%d" %(self.kernel.fotoalbaupurl, self.kernel.auth, sid)
		data = ""

		for key in d:
			data += "--%s\r\n" %(boundary)
			data += "Content-Disposition: form-data; name=\"%s\"\r\n\r\n" %(key)
			data += "%s\r\n" %(d[key])
			
		data += "--%s\r\n" %(boundary)
		data += "Content-Disposition: form-data; name=\"photo1\"; filename=\"%s\"\r\n" %(FILE);
		data += "Content-Type: image/jpeg\r\n\r\n"
		
		img = open (FILE, 'r')
		binary = img.read()
		img.close()
		
		data += binary
		data += "\r\n--%s--\r\n" %(boundary)
		
		req = urllib2.Request(url=URL, data=data)
		req.add_header('Content-type','multipart/form-data; boundary=' + boundary)
		
		try:
			r = urllib2.urlopen(req)
		except:
			raise
		
		upl = r.read()
		#newurl = re.findall("window.top.location.href = '([^']*)'", upl)[0]
		
		try:
			#photoUrl = self.kernel.urlopen("%s%s/%s" %(self.kernel.fotoalbaupurl, self.kernel.auth, newurl))
			r = self.kernel.urlopen("%s%s/uploaddone.php?sessid=%d&mes=201&redir=1&step=1&uploader=1" %(self.kernel.fotoalbaupurl, self.kernel.auth, sid))
		except:
			raise
		
		#pid = re.findall("pid\[\]=(\d+)$", photoUrl)[0]
		pid = r.read()
		
		params = {
			'pid': pid,
			'name': image['title'].encode('iso-8859-2'),
			'comment': image['desc'].encode('iso-8859-2'),
			'keywords': '',
			'access1': 1,
			'id_category': 0,
			'id_album': self.kernel.aid,
			'_Button_Send': 1
		}
		
		url = "%s%s/ephoto.php?%s" %(self.kernel.fotoalbaurl, self.kernel.auth, unicode_urlencode(params))
		
		try:
			data = self.kernel.urlopen(url)
		except:
			raise

class RedirectHandler(urllib2.HTTPRedirectHandler):
	def http_error_302(self, req, fp, code, msg, headers):
		try:
			return headers.getheader("Location")
		except(TypeError):
			pass

def unicode_urlencode(params):
	if isinstance(params, dict):
		params = params.items()
		return urllib.urlencode([(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params]).replace('%3A',':')
